<!--
 * @Description: 编辑维修配件
 * @Autor: 何兴家
 * @Date: 2020-12-28 15:07:10
 * @LastEditors: 马毅
 * @LastEditTime: 2021-04-13 17:50:24
-->
<template>
  <div>
    <FormPanel ref="form" :list="formList" :isSubmitBtn="false"></FormPanel>
    <FilterTable
      ref="table"
      columnsRef="repair_repairReception_customer_editRepairPart"
      height="auto"
      :columns="columns"
      :isSelectColumn="false"
      :isPagination="false"
      :dataSource="bottomTableDataSource"
      :onSyncTableData="handleSyncTableData"
      :onColumnsChange="columns => (this.columns = columns)"
    >
    </FilterTable>
    <BaseDialog :visible.sync="showPanel" title="标题" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"> </BaseDialog>

    <div class="dialogBottmView">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { confirmAction, notifyAction, findFormItem, findTableItem } from '@/utils';

import { queryPartDetailInfoByPartNo } from '@/api/repair/common';

export default {
  props: ['repairLabourDict', 'chargePartitionDict', 'editPartData', 'rechargeableCodes', 'repairPermission'],
  mixins: [dictionary],
  data() {
    this.priceTypeCodeObj = {
      82481001: 'NOT_TAX_INSTRUCT_PRICE',
      82481002: 'PLAN_PRICE',
      82481003: 'COST_PRICE',
      82481004: 'INSURANCE_PRICE',
      82481005: 'CLAIM_PRICE',
      82481006: 'LATEST_PRICE'
    };

    return {
      formList: this.createFormList(),
      columns: this.createTableColumns(),
      fetchapi: () => {},
      fetchParams: { xhrAbort: true },
      showPanel: false,
      syncTableData: [], // 同步的table数据
      bottomTableDataSource: [] // table数据源
    };
  },
  computed: {
    // 价格类型字段
    priceTypeCode() {
      return this.priceTypeCodeObj[findFormItem(this.formList, 'PRICE_TYPE').initialValue];
    },
    // 价格系数
    priceRate() {
      return findFormItem(this.formList, 'PRICE_RATE').initialValue;
    },
    // 基础价格
    basePrice() {
      return this.editPartData[this.priceTypeCode];
    }
  },
  watch: {
    // 监听维修类型的改变
    priceTypeCode(newVal) {
      this.calcSalePriceAndAmount();
    }
  },
  mounted() {
    findFormItem(this.formList, 'CHARGE_PARTITION_CODE').itemList = this.chargePartitionDict;
    findFormItem(this.formList, 'LABOUR_CODE').itemList = this.repairLabourDict;
    this.initData();
    this.initPirceEditPermission();
    // console.log(this.editPartData, 'hexj001');
  },
  methods: {
    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'STORAGE_CODE',
          disabled: true,
          itemList: []
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'PART_NO',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'PART_NAME',
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '主要配件',
          fieldName: 'IS_MAIN_PART',
          // itemList: this.createDictList(1004).map(item => ({ text: item.text, value: item.value + '' })),
          itemList: this.createDictList(1004),
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '价格类型',
          fieldName: 'PRICE_TYPE',
          disabled: false,
          itemList: this.createDictList(8248, [82481006]),
          rules: [{ required: true, message: '价格类型不能为空', trigger: 'blur' }],
          initialValue: ''
        },
        {
          type: 'INPUT_NUMBER',
          label: '价格系数',
          isControls: false,
          disabled: false,
          fieldName: 'PRICE_RATE',
          rules: [{ required: true, message: '价格系数不能为空', trigger: 'blur' }],
          min: 1,
          change: val => {
            this.$nextTick(() => {
              this.calcSalePriceAndAmount();
            });
          }
          // initialValue: 1
        },
        {
          type: 'INPUT_NUMBER',
          label: '发料单价',
          fieldName: 'PART_SALES_PRICE',
          precision: 2,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT_NUMBER',
          label: '发料数量',
          isControls: false,
          fieldName: 'PART_QUANTITY',
          change: this.handleQuantityChange
          // initialValue: ''
        },
        {
          type: 'INPUT_NUMBER',
          label: '发料金额',
          precision: 2,
          disabled: true,
          fieldName: 'PART_SALES_AMOUNT',
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '收费区分',
          fieldName: 'CHARGE_PARTITION_CODE',
          itemList: [],
          change: this.handleChargePartitionCodeChange
        },
        {
          type: 'SELECT',
          label: '维修项目',
          fieldName: 'LABOUR_CODE',
          itemList: [],
          change: this.handleRepairLabourChange
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'REMARK'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '终端建议零售VIP价格',
          dataIndex: 'notTaxInstructPrice'
        },
        {
          title: '常规订货价',
          dataIndex: 'planPrice'
        },
        {
          title: '终端建议零售价格',
          dataIndex: 'insurancePrice'
        },
        {
          title: '最大库存',
          dataIndex: 'maxStock'
        },
        {
          title: '最小库存',
          dataIndex: 'minStock'
        },
        {
          title: '账面库存',
          dataIndex: 'stockQuantity'
        },
        {
          title: '可用库存',
          dataIndex: 'usableStock'
        },
        {
          title: '锁定量',
          dataIndex: 'lockedQuantity'
        },
        {
          title: '配件类别',
          dataIndex: 'partGroupCode',
          dictItems: this.createDictList(8247)
        },
        {
          title: '单位',
          dataIndex: 'unitName'
        },
        {
          title: '车型',
          dataIndex: 'model',
          dictItems: []
        }
      ];
    },
    // 同步table数据
    handleSyncTableData(list) {
      this.syncTableData = list;
    },
    // 初始化价格编辑权限
    initPirceEditPermission() {
      if (this.repairPermission) {
        if (!this.repairPermission.includes('12111033')) {
          findFormItem(this.formList, 'PRICE_RATE').disabled = true;
          findFormItem(this.formList, 'PRICE_TYPE').disabled = true;
        }
      }
    },
    // 初始化数据
    initData() {
      let dataCopy = _.cloneDeep(this.editPartData);
      this.formList.forEach(item => {
        item.initialValue = dataCopy[item.fieldName];
      });
      this.queryPartDetailByPartNo(this.editPartData.STORAGE_CODE, this.editPartData.PART_NO);
    },
    // 根据配件信息查询详情
    async queryPartDetailByPartNo(storageCode, partNo) {
      this.$refs.table.START_LOADING();
      try {
        let res = await queryPartDetailInfoByPartNo({ partNo, storageCode });
        if (res.resultCode == 200 && res.data) {
          this.bottomTableDataSource = [res.data];
        }
      } catch (err) {
        console.log(err, '获取配件详情失败');
      } finally {
        this.$refs.table.STOP_LOADING();
      }
    },
    // 发料数量变化
    handleQuantityChange(val) {
      this.handleChargePartitionCodeChange();
    },
    // 维修项目变化
    handleRepairLabourChange(val) {
      findFormItem(this.formList, 'CHARGE_PARTITION_CODE').initialValue = this.repairLabourDict.find(item => item.value == val).defaultChargePartition || 'Z';
      this.handleChargePartitionCodeChange();
    },
    // 收费区分变化
    handleChargePartitionCodeChange() {
      this.$nextTick(() => {
        // 此处暂为计算应收
        // let chargePartitionCode = findFormItem(this.formList, 'CHARGE_PARTITION_CODE').initialValue;
        // findFormItem(this.formList, 'PART_SALES_AMOUNT').initialValue = this.rechargeableCodes.includes(chargePartitionCode)
        //   ? findFormItem(this.formList, 'PART_SALES_PRICE').initialValue * findFormItem(this.formList, 'PART_QUANTITY').initialValue
        //   : 0;
        findFormItem(this.formList, 'PART_SALES_AMOUNT').initialValue = findFormItem(this.formList, 'PART_SALES_PRICE').initialValue * findFormItem(this.formList, 'PART_QUANTITY').initialValue;
      });
    },
    // 价格系数变化
    handlePriceRateChange(val) {
      findFormItem(this.formList, 'PART_SALES_PRICE').initialValue = findFormItem(this.formList, 'PART_SALES_PRICE').initialValue * val;
      this.handleChargePartitionCodeChange();
    },
    // 重新计算发料单价及发料金额
    calcSalePriceAndAmount() {
      findFormItem(this.formList, 'PART_SALES_PRICE').initialValue = this.basePrice * this.priceRate;
      findFormItem(this.formList, 'PART_SALES_AMOUNT').initialValue = this.basePrice * this.priceRate * (findFormItem(this.formList, 'PART_QUANTITY').initialValue || 0);
    },
    // 点击取消
    handleCancel() {
      this.$emit('close');
    },
    // 点击确定
    async handleConfirm() {
      let formData = await this.$refs.form.GET_FORM_DATA();
      if (formData[0]) return;
      // 带出前处理部分数据
      let dataObj = Object.assign({}, this.editPartData, formData[1]);
      dataObj.RECEIVE_AMOUNT = this.rechargeableCodes.includes(dataObj.CHARGE_PARTITION_CODE) ? dataObj.PART_SALES_AMOUNT : 0;
      this.$emit('onConfirm', dataObj);
    }
  }
};
</script>

<style scoped></style>
